<?php

class Pharing_Flickr extends Pharing_Service
{
	protected $_apiKey;
	
	public function __construct($apiKey)
	{
		$this->_apiKey = $apiKey;
	}
	
	public function fetch($user)
	{
		$user = $this->_getUserByEmail($user);
		if ($user === false) {
			throw new Pharing_UserNotFoundException();
		}
		$photos = array();
		foreach ($this->_getPublicPhotos($user) as $photo) {
			$photos[] = $this->_constructPhotoUrl($photo->attributes());
		}
		return $photos;
	}
	
	protected function _constructPhotoUrl($photo)
	{
		$p = $photo;
		$url = 'http://farm%s.static.flickr.com/%s/%s_%s.jpg';
		return sprintf($url, $p->farm, $p->server, $p->id, $p->secret);
	}
	
	protected function _getUserByEmail($email)
	{
		$params = array('find_email' => $email);
		$findByEmail = $this->_callApi('people.findByEmail', $params);
		if (!preg_match('/id="([^"]+)"/', $findByEmail, $match)) {
			return false;
		}
		return $match[1];		
	}
	
	protected function _callApi($method, array $params = array())
	{
		$params['api_key'] = $this->_apiKey;
		$params['method'] = "flickr.$method";		
		$url = 'http://api.flickr.com/services/rest/?';
		return $this->_urlGetContents($url . http_build_query($params));		
	}
	
	protected function _getPublicPhotos($user)
	{
		$params = array('user_id' => $user);
		$getPublicPhotos = $this->_callApi('people.getPublicPhotos', $params);
		$xml = new SimpleXMLElement($getPublicPhotos);
		if (!isset($xml->photos)) {
			return array();
		}
		return $xml->photos->children();
	}
}